package com.greenhouse.service.impl;

import com.greenhouse.service.EnvironmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.greenhouse.model.Environment;
import com.greenhouse.service.DataService;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;

@Service
public class DataServiceImpl implements DataService {
    private static final Logger logger = LoggerFactory.getLogger(DataServiceImpl.class);
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private EnvironmentService environmentService;

    @Override
    public void insertData(String[] topic, MqttMessage message) {
        logger.info("topic: {}_{}_{}", topic[1], topic[2], topic[3]);
        String m = new String(message.getPayload());
        String name = "e_" + topic[2] + "_" + topic[3];
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(dateFormat);
        try {
            Environment environment = objectMapper.readValue(m, Environment.class);
            environmentService.insertEnvironment(name,environment);
        } catch (Exception e) {
            logger.error("Failed to parse JSON data", e);
        }
    }
}